package cn.cqautotest.cqviehelper.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.InputFilter;
import android.view.View;
import android.widget.ImageView;

import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.util.Pair;
import androidx.fragment.app.FragmentActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.widget.layout.SettingBar;
import com.vondear.rxfeature.tool.RxQRCode;
import com.zhuangfei.timetable.model.Schedule;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.cqautotest.cqviehelper.R;
import cn.cqautotest.cqviehelper.base.BaseActivity;
import cn.cqautotest.cqviehelper.base.BaseFragment;
import cn.cqautotest.cqviehelper.config.Constants;
import cn.cqautotest.cqviehelper.interfaces.ICourseCallback;
import cn.cqautotest.cqviehelper.presenter.CoursePresenter;
import cn.cqautotest.cqviehelper.ui.activity.HomeActivity;
import cn.cqautotest.cqviehelper.ui.activity.ImageActivity;
import cn.cqautotest.cqviehelper.ui.activity.SettingActivity;
import cn.cqautotest.cqviehelper.ui.activity.TakePhotoActivity;
import cn.cqautotest.cqviehelper.ui.activity.WebViewActivity;
import cn.cqautotest.cqviehelper.ui.dialog.AddressDialog;
import cn.cqautotest.cqviehelper.ui.dialog.InputDialog;
import cn.cqautotest.cqviehelper.ui.dialog.ToastDialog;
import cn.cqautotest.cqviehelper.utils.StartAppUtils;
import cn.cqautotest.cqviehelper.utils.StringJoinUtils;
import cn.cqautotest.cqviehelper.views.TreasureView;
import de.hdodenhof.circleimageview.CircleImageView;

@SuppressLint("NonConstantResourceId")
public class MeFragment extends BaseFragment<BaseActivity> implements ICourseCallback {

    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.container)
    View container;
    @BindView(R.id.treasureView)
    TreasureView treasureView;
    @BindView(R.id.iv_person_data_avatar)
    CircleImageView mAvatarView;
    @BindView(R.id.person_data_name)
    SettingBar mNameView;
    @BindView(R.id.person_data_id)
    SettingBar mIDView;
    @BindView(R.id.person_data_user_type)
    SettingBar mUserTypeView;
    @BindView(R.id.person_data_class)
    SettingBar mClassView;
    @BindView(R.id.person_data_address)
    SettingBar mAddressView;
    @BindView(R.id.person_data_qq)
    SettingBar mQQView;
    @BindView(R.id.person_data_setting)
    SettingBar mSettingView;

    /**
     * 省
     */
    private String mProvince = "重庆市";
    /**
     * 市
     */
    private String mCity = "重庆市";
    /**
     * 区
     */
    private String mArea = "江津区";

    private CoursePresenter mCoursePresenter;
    private InputDialog.Builder mIdBuilder;
    private InputDialog.Builder mQQBuilder;
    private String mNickName;
    private String mUserId;
    private String mQQ;
    private String mAvatarUrl;
    private ImageView mQrCodeView;

    public static MeFragment getInstance() {
        return new MeFragment();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_me;
    }

    @Override
    protected void initPresenter() {
        mCoursePresenter = CoursePresenter.getInstance();
        mCoursePresenter.registered(this);
    }

    @Override
    protected void initView(View rootView) {
        String userType = mSpUserInfoSetting.getString(Constants.USER_TYPE, "STUDENT");
        if (userType == null) userType = "";
        if (userType.equals("STUDENT")) {
            userType = "学生";
        }
        if (userType.equals("TEACHER")) {
            userType = "教师";
        }
        mUserTypeView.setRightText(userType);
        mQrCodeView = treasureView.findViewById(R.id.iv_qr_code);
    }

    @Override
    protected void initData() {
        reSetUpUserInfo();
    }

    @Override
    protected void initEvent() {
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                FragmentActivity activity = getActivity();
                if (activity instanceof HomeActivity) {
                    ((HomeActivity) activity).back2PreviousUI();
                }
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        mQrCodeView.setOnLongClickListener(v -> {
            Bitmap qrCodeBitmap = ImageUtils.view2Bitmap(mQrCodeView);
            String qrCodePath = StringJoinUtils.join(PathUtils.getExternalPicturesPath(), "/", "课程二维码.png");
            File qrCodeFile = new File(qrCodePath);
            boolean isSave = ImageUtils.save(qrCodeBitmap, qrCodeFile, Bitmap.CompressFormat.PNG);
            Intent shareIntent = IntentUtils.getShareImageIntent(qrCodeFile);
            startActivity(shareIntent);
            ToastUtils.showShort(isSave ? "课程二维码已保存至相册~" : "课程二维码保存失败！");
            return true;
        });
        treasureView.setOnStateChangedListener(new TreasureView.OnStateChanged() {

            @Override
            public void onTreasureClick(View view) {
                //隐藏的View被点击时触发
                // TODO: 2020/8/5 打开隐藏的彩蛋（尚未开发）
            }

            @Override
            public void onOpen() {
                //Log.d(TAG, "onClose: ========> 打开了");
                ToastUtils.showShort("长按课程二维码即可保存分享");
            }

            @Override
            public void onClose() {
                //Log.d(TAG, "onClose: ========> 关闭了");
                //ToastUtils.showShort("关闭了");
            }
        });
    }

    @SuppressWarnings("unchecked")
    @OnClick({R.id.iv_person_data_avatar, R.id.person_data_name, R.id.person_data_id, R.id.person_data_user_type,
            R.id.person_data_address, R.id.person_data_qq, R.id.takePhotoSettingBar, R.id.person_data_make_complaints,
            R.id.person_data_donation, R.id.person_data_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_person_data_avatar:
                ActivityOptionsCompat activityOptions = ActivityOptionsCompat.
                        makeSceneTransitionAnimation(getAttachActivity(), new Pair<>(view, "CONTENT"));
                ArrayList<String> images = new ArrayList<>();
                images.add(mAvatarUrl);
                //ActivityCompat是android支持库中用来适应不同android版本的
                ActivityCompat.startActivity(getAttachActivity(),
                        ImageActivity.getIntent(getAttachActivity(), images), activityOptions.toBundle());
                break;
            case R.id.person_data_name:
                new InputDialog.Builder(mContext)
                        // 标题可以不用填写
                        .setTitle(getString(R.string.personal_data_name_hint))
                        .setContent(String.valueOf(mNickName))
                        .setHint(getString(R.string.personal_data_name_hint))
                        //.setConfirm("确定")
                        // 设置 null 表示不显示取消按钮
                        //.setCancel("取消")
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener((dialog, content) -> {
                            if (!mNameView.getRightText().equals(content)) {
                                mNameView.setRightText(content);
                                //将更改后的昵称存储到本地
                                mSpUserInfoSetting.edit().putString(Constants.NICK_NAME, content).apply();
                            }
                        })
                        .show();
                break;
            case R.id.person_data_id:
                if (mIdBuilder == null) {
                    mIdBuilder = new InputDialog.Builder(mContext)
                            // 标题可以不用填写
                            .setTitle(getString(R.string.personal_data_id_hint))
                            .setContent(String.valueOf(mUserId))
                            .setHint(getString(R.string.personal_data_id_hint))
                            //.setConfirm("确定")
                            // 设置 null 表示不显示取消按钮
                            //.setCancel("取消")
                            // 设置点击按钮后不关闭对话框
                            //.setAutoDismiss(false)
                            //设置是否可以通过点击空白区域取消
                            .setCanceledOnTouchOutside(false)
                            .setListener((dialog, content) -> {
                                if (content.matches("^\\d{10}$")) {
                                    if (!mIDView.getRightText().equals(content)) {
                                        mIDView.setRightText(content);
                                        //将更改后的学工号存储到本地
                                        mSpUserInfoSetting.edit().putString(Constants.USER_ID, content).apply();
                                        if (mCoursePresenter != null) {
                                            mCoursePresenter.clearLocalCourseList();
                                            //通知注册者，用户信息发生了变化
                                            mCoursePresenter.onUserInfoChanged();
                                        }
                                    }
                                } else {
                                    ToastUtils.showLong("请输入长度为10位的学工号！");
                                }
                            });
                }
                mIdBuilder.getInputView().setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
                    //限制输入的内容只能为数字
                    String message = source.toString();
                    return !message.matches("^\\d$") ? "" : null;
                    //限制输入的长度最大为10
                }, new InputFilter.LengthFilter(10)});
                mIdBuilder.show();
                break;
            case R.id.person_data_user_type:
                List<String> userTypeList = new ArrayList<>();
                userTypeList.add("学生");
                userTypeList.add("教师");
                OptionsPickerBuilder userTypeBuilder = new OptionsPickerBuilder(mContext, (OnOptionsSelectListener) (options1, options2, options3, v) -> {
                    String userType = userTypeList.get(options1);
                    mUserTypeView.setRightText(userType);
                    if (userType.equals("学生")) {
                        userType = "STUDENT";
                    }
                    if (userType.equals("教师")) {
                        userType = "TEACHER";
                    }
                    mSpUserInfoSetting.edit().putString(Constants.USER_TYPE, userType).apply();
                    if (mCoursePresenter != null) {
                        mCoursePresenter.clearLocalCourseList();
                        //通知注册者，用户信息发生了变化
                        mCoursePresenter.onUserInfoChanged();
                    }
                }).isAlphaGradient(true);
                OptionsPickerView<String> pickerView = userTypeBuilder.build();
                pickerView.setPicker(userTypeList);
                pickerView.show();
                break;
            case R.id.person_data_qq:
                if (mQQBuilder == null) {
                    mQQBuilder = new InputDialog.Builder(mContext)
                            // 标题可以不用填写
                            .setTitle(getString(R.string.personal_data_qq_hint))
                            .setContent(String.valueOf(mQQ))
                            .setHint(getString(R.string.personal_data_qq_hint))
                            //.setConfirm("确定")
                            // 设置 null 表示不显示取消按钮
                            //.setCancel("取消")
                            // 设置点击按钮后不关闭对话框
                            //.setAutoDismiss(false)
                            //设置是否可以通过点击空白区域取消
                            .setCanceledOnTouchOutside(false)
                            .setListener((dialog, content) -> {
                                if (!mQQView.getRightText().equals(content)) {
                                    mQQ = content;
                                    mQQView.setRightText(content);
                                    //将更改后的QQ号存储到本地
                                    mSpUserInfoSetting.edit().putString(Constants.QQ, content).apply();
                                    loadAvatar();
                                }
                            });
                }
                mQQBuilder.getInputView().setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
                    //限制输入的内容只能为数字
                    String message = source.toString();
                    return !message.matches("^\\d$") ? "" : null;
                    //限制输入的长度最大为10
                }});
                mQQBuilder.show();
                break;
            case R.id.person_data_address:
                new AddressDialog.Builder(mContext)
                        //.setTitle("选择地区")
                        // 设置默认省份
                        .setProvince(mProvince)
                        // 设置默认城市（必须要先设置默认省份）
                        .setCity(mCity)
                        // 不选择县级区域
                        //.setIgnoreArea()
                        .setListener((dialog, province, city, area) -> {
                            String address = province + city + area;
                            if (!mAddressView.getRightText().equals(address)) {
                                mProvince = province;
                                mCity = city;
                                mArea = area;
                                mAddressView.setRightText(address);
                            }
                        }).show();
                break;
            case R.id.takePhotoSettingBar:
                new ToastDialog.Builder(mContext).setMessage("拍照").create().show();
                startActivity(TakePhotoActivity.class);
                break;
            case R.id.person_data_make_complaints:
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(Constants.OPEN_ID, mUserId);
                intent.putExtra(Constants.NICK_NAME, mNickName);
                intent.putExtra(Constants.HEADER_IMG_URL, mAvatarUrl);
                intent.putExtra(Constants.STR_URL, Constants.MAKE_COMPLAINTS_URL);
                startActivity(intent);
                break;
            case R.id.person_data_donation:
                StartAppUtils.startAliPay(mContext);
                break;
            case R.id.person_data_setting:
                startActivity(SettingActivity.class);
                break;
            default:
                break;
        }
    }

    /**
     * 在界面重新可见的时候更改页面的主题
     */
    @Override
    protected void uiReShowing() {
        FragmentActivity activity = getActivity();
        if (activity instanceof HomeActivity) {
            HomeActivity homeActivity = (HomeActivity) activity;
            homeActivity.resetBgState();
        }
        mUserId = mSpUserInfoSetting.getString(Constants.USER_ID, "");
        mIDView.setRightText(mUserId);
        mNickName = mSpUserInfoSetting.getString(Constants.NICK_NAME, "");
        mNameView.setRightText(mNickName);
        String address = mSpUserInfoSetting.getString(Constants.ADDRESS, mProvince + mCity + mArea);
        mAddressView.setRightText(address);
        mQQ = mSpUserInfoSetting.getString(Constants.QQ, "");
        mQQView.setRightText(mQQ);
        loadAvatar();
    }

    /**
     * 加载用户头像
     */
    private void loadAvatar() {
        //拼接头像地址
        mAvatarUrl = StringJoinUtils.join("http://q.qlogo.cn/headimg_dl?bs=qq&dst_uin=", mQQ, "&src_uin=www.jlwz.cn&fid=blog&spec=100");
        //mAvatarUrl = "https://q1.qlogo.cn/g?b=qq&nk=" + mQQ + "&src_uin=www.jlwz.cn&s=0";
        //mAvatarUrl = "http://q2.qlogo.cn/headimg_dl?dst_uin=" + mQQ + "&spec=100";
        Glide.with(mContext)
                .load(mAvatarUrl)
                .placeholder(R.mipmap.ic_head_placeholder)
                .error(R.mipmap.ic_head_placeholder)
                .circleCrop()
                .into(mAvatarView);
    }

    @Override
    protected void release() {
        if (mCoursePresenter != null) mCoursePresenter.unRegistered(this);
    }

    @Override
    public void reSetUpUserInfo() {
        String schoolYear = mSpUserInfoSetting.getString(Constants.SCHOOL_YEAR, "2020-2021");
        int term = mSpUserInfoSetting.getInt(Constants.TERM, 1);
        JSONObject courseJson = new JSONObject();
        try {
            courseJson.put(Constants.SCHOOL_YEAR, schoolYear);
            courseJson.put(Constants.TERM, term);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RxQRCode.createQRCode(courseJson.toString(), mQrCodeView);
    }

    @Override
    public void onCourseLoaded(List<Schedule> schedules) {

    }

    @Override
    public void onRequestError(Exception e) {

    }
}
